package com.util;

import java.sql.*;

public class JDBC_Util {
    public static final String URL ="jdbc:mysql://192.168.118.129:3306/db_erp";
    public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    public static final String USER = "root";
    public static final String PASW = "123456";

    static  {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection()  {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL,USER,PASW);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    public static void close(ResultSet rs, Connection conn, Statement state){
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (state != null) {
                state.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static int update(String sql){
        int m = 0;
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            m = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            close(null,conn,ps);
        }
        return m;
    }

    public static int returnMaxId(String sql){
        int id = 0;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            if (rs.next()) {
                id = rs.getInt("max(id)");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            close(rs,conn,ps);
        }
        return id;
    }

}
